package com.zsn.demo.test.condition;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zsn
 * @CreateTime: 2022/12/9 0:00
 * @Description:
 */
public class conditiontest1 {

    static class MyService{
        private Lock lock =  new ReentrantLock();
        private Condition condition = lock.newCondition();
        private boolean flag = true;

        // 打印横线
        public void printOne(){
            try {
                lock.lock();
                while (flag){
                    System.out.println(Thread.currentThread().getName() + "   waiting");
                    condition.await();
                }
                //flag 为 false 时打印
                System.out.println(Thread.currentThread().getName() + " ---------------- ");
                flag = true;
                condition.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

        // 打印星号
        public void printTwo(){
            try {
                lock.lock();
                while (!flag){
                    System.out.println(Thread.currentThread().getName() + "  waiting");
                    condition.await();
                }
                //flag 为 false 时打印
                System.out.println(Thread.currentThread().getName() + " ************* ");
                flag = false;
                condition.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

        public static void main(String[] args) {
            MyService myService = new MyService();

            //
            for (int i = 0; i < 10; i++) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < 10; i++) {
                            myService.printOne();
                        }
                    }
                }).start();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < 10; i++) {
                            myService.printTwo();
                        }
                    }
                }).start();
            }

        }
    }
}

